package cn.heyige.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.heyige.backend.entity.AiSessionDO;
import cn.heyige.backend.mapper.AiSessionMapper;
import cn.heyige.backend.service.AiSessionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * AI会话服务实现类 - 精简版
 *
 * 专注于核心AI会话管理功能，提高系统性能和可维护性
 * 增强数据验证和错误处理
 *
 * @author CodeBuddy
 */
@Service("aiSessionService")
@Slf4j
@RequiredArgsConstructor
public class AiSessionServiceImpl extends ServiceImpl<AiSessionMapper, AiSessionDO> implements AiSessionService {
    
    private static final int DEFAULT_PAGE_SIZE = 20;
    private static final int MAX_PAGE_SIZE = 100;
    
    @Override
    public IPage<AiSessionDO> getSessionsByUserId(Long userId, Integer pageNum, Integer pageSize) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 设置默认分页参数
        int actualPageNum = pageNum != null ? pageNum : 1;
        int actualPageSize = pageSize != null ? Math.min(pageSize, MAX_PAGE_SIZE) : DEFAULT_PAGE_SIZE;

        try {
            return page(new Page<>(actualPageNum, actualPageSize),
                    new LambdaQueryWrapper<AiSessionDO>()
                            .orderByDesc(AiSessionDO::getCreateTime));
        } catch (Exception e) {
            log.error("获取用户AI会话失败: userId={}, pageNum={}, pageSize={}",
                    userId, actualPageNum, actualPageSize, e);
            throw new RuntimeException("获取用户AI会话失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AiSessionDO createSession(Long userId, String title) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        if (!StringUtils.hasText(title)) {
            throw new IllegalArgumentException("会话标题不能为空");
        }

        try {
            AiSessionDO session = new AiSessionDO();
            session.setTitle(title);
            session.setCreateTime(LocalDateTime.now());
            session.setUpdateTime(LocalDateTime.now());
            save(session);
            return session;
        } catch (Exception e) {
            log.error("创建AI会话失败: userId={}, title={}", userId, title, e);
            throw new RuntimeException("创建AI会话失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSessionTitle(Integer sessionId, String title) {
        // 参数校验
        if (sessionId == null) {
            throw new IllegalArgumentException("会话ID不能为空");
        }

        if (!StringUtils.hasText(title)) {
            throw new IllegalArgumentException("会话标题不能为空");
        }

        try {
            AiSessionDO session = getById(sessionId);
            if (session == null) {
                log.warn("更新会话标题失败：会话不存在，sessionId={}", sessionId);
                return false;
            }

            session.setTitle(title);
            session.setUpdateTime(LocalDateTime.now());
            return updateById(session);
        } catch (Exception e) {
            log.error("更新会话标题失败: sessionId={}, title={}", sessionId, title, e);
            throw new RuntimeException("更新会话标题失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSession(Integer sessionId, Long userId) {
        // 参数校验
        if (sessionId == null) {
            throw new IllegalArgumentException("会话ID不能为空");
        }

        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        try {
            AiSessionDO session = getById(sessionId);
            if (session == null) {
                log.warn("删除会话失败：会话不存在，sessionId={}", sessionId);
                return false;
            }

            return removeById(sessionId);
        } catch (Exception e) {
            log.error("删除会话失败: sessionId={}, userId={}", sessionId, userId, e);
            throw new RuntimeException("删除会话失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSessionsByUserId(Long userId) {
        // 参数校验
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        try {
            // 由于AiSessionDO中没有userId字段，所以这里直接返回false
            log.warn("AiSessionDO中没有userId字段，无法根据用户ID删除会话");
            return false;
        } catch (Exception e) {
            log.error("删除用户会话失败: userId={}", userId, e);
            throw new RuntimeException("删除用户会话失败: " + e.getMessage());
        }
    }
}
